package br.com.fiap.goaround.dao;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Transaction;

import br.com.fiap.goaround.to.TrafficTO;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class TrafficDAO {

	public TrafficDAO() {
	}

	@SuppressWarnings("unchecked")
	public void insertAll(Collection<TrafficTO> lista) {

		PersistenceManager pm = PMF.get().getPersistenceManager();
 
		UserService userService = UserServiceFactory.getUserService();
		@SuppressWarnings("unused")
		User user = userService.getCurrentUser();

		Iterator it = lista.iterator();

		while (it.hasNext()) {
		    Transaction tx = pm.currentTransaction();
		    tx.begin();
			TrafficTO tse = (TrafficTO) it.next();
			pm.makePersistent(tse);
			tx.commit();
		}
		
		pm.close();

	}

	public void deleteAll() {

	
		try {
			
		DateFormat dtf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
		Long tempoexp = System.currentTimeMillis();
		Date dataexp = new Date();

		System.out.println("Inicio do Expurgo: " + dtf.format(dataexp));
		PersistenceManager pm = PMF.get().getPersistenceManager();
		List<TrafficTO> t = findAll();
        for (TrafficTO to : t) {
        	Transaction tx = pm.currentTransaction();
        	tx.begin();
        	TrafficTO to1 = pm.getObjectById( to.getClass(), to.getId()); //casting to generic type
        	pm.deletePersistent( to1 ); 
        	
        	//pm.deletePersistent(to);
        	tx.commit();
		}
		//pm.deletePersistentAll();
		pm.close();
		dataexp = new Date();

		System.out.println("Fim do Expurgo: " + dtf.format(dataexp));
		System.out.println("Tempo Total do Expurgo: "
				+ (System.currentTimeMillis() - tempoexp));
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
	
	@SuppressWarnings("unchecked")
	public List<TrafficTO> findAll() {

		String query = "select from " + TrafficTO.class.getName();
		List<TrafficTO> trafficList = new ArrayList<TrafficTO>();
		
		PersistenceManager pm = PMF.get().getPersistenceManager();
		trafficList = (List<TrafficTO>) pm.newQuery(query).execute();
		List<TrafficTO> trafficListX = new ArrayList<TrafficTO>();
		
		Iterator it = trafficList.iterator();

		// Valida informacoes antes de entregar
		while(it.hasNext()){
			
			TrafficTO tx = (TrafficTO) it.next();
			
			if(tx.getEndereco()!=null)
				trafficListX.add(tx);
	
		}
		pm.close();
		
		return trafficListX;
	}

}
